﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.RBAC;
using B.S.BasicData.Api.Read.DTO;
using B.S.BasicData.Domian.Entities.Account;
using B.S.BasicData.Domian.Entities.RBAC;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using System.Linq;

namespace B.S.BasicData.Api.Read.Application.Handler.RBAC
{
    class FTUserNameHandler : IRequestHandler<FTUserNameCommand, ApiResult<FTUserNameDTO>>
    {
        private readonly IBaseRepository<AccountModel> accpuntRepo;
        private readonly IBaseRepository<UserRoleModel> userroleRepo;
        private readonly IMapper mapper;

        public FTUserNameHandler(IBaseRepository<AccountModel> accpuntRepo, IBaseRepository<UserRoleModel> userroleRepo, IMapper mapper)
        {
            this.accpuntRepo = accpuntRepo;
            this.userroleRepo = userroleRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<FTUserNameDTO>> Handle(FTUserNameCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<FTUserNameDTO>();
            FTUserNameDTO dto = new FTUserNameDTO();
            List<long> userlist = userroleRepo.GetAll().Where(x => x.RoleId == request.RoleId).Select(x => Convert.ToInt64(x.UserId)).ToList();
            if (userlist.Count() != 0)
            {
                var deptid = (accpuntRepo.GetAll().FirstOrDefault(x => x.Id == userlist[0])!).bid;
                dto.uselist = userlist;
                dto.Deptid = Convert.ToInt32(deptid);
                dto.UserName = accpuntRepo.GetAll().Where(x => userlist.Contains(x.Id)).ToList();
                res.Data = dto;
                return Task.FromResult(res);
            }
            res.Data = dto;
            res.Code = ApiEnum.Ok;
            res.Message = "反填成功";
            return Task.FromResult(res);
        }
    }
}
